/** 
* Copyright (C) 2012-2017 ZEEI Inc.All Rights Reserved.
* 项目名称：common
* 文件名称：HttpRequestUtil.java
* 包  名 称：com.zeei.common.utils
* 文件描述：http请求工具类
* 创建日期：2017年8月3日上午9:39:11
* 
* 修改历史
* 1.0 sunqian 2017年8月3日上午9:39:11 创建文件
*
*/
package com.zeei.ems.base.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @类型名称：HttpRequestUtil
 * @类型描述：http请求工具类
 * @功能描述：提供http请求工具方法
 * @创建作者：sunqian
 */
public class HttpRequestUtil {
	private static Logger LOGGER = LoggerFactory.getLogger(HttpRequestUtil.class);
	private HttpRequestUtil() {

	}

	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param url
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url, String param) {
		String bfsUrl = getBfsUrl(url);
		String result = StringUtil.empty();
		BufferedReader in = null;
		try {
			String urlNameString = bfsUrl + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			//Map<String, List<String>> map = connection.getHeaderFields();
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			LOGGER.error(String.format("HttpRequestUtil.sendGet:%s", e));
		}finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				LOGGER.error(String.format("HttpRequestUtil.sendGet finally:%s", e2));
			}
		}

		return result;
	}

	/**
	 * 向指定 URL 发送POST方法的请求
	 *
	 *            发送请求的 URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(HttpServletRequest request, String strURL, String param) {
		try {
			String sessionId = getSidCookieInfo(request, "sid");
			String ssoSid = getSidCookieInfo(request, "JSESSIONID");
			return httpPost(sessionId, strURL, param, ssoSid);
		} catch (Exception e) {
			LOGGER.error(String.format("HttpRequestUtil.sendPost:%s", e));
			return "";
		}
	}

	public static String sendPost(String sessionId, String strURL, String param) {
		try {
			return httpPost(sessionId, strURL, param, StringUtils.EMPTY);
		} catch (Exception e) {
			LOGGER.error(String.format("HttpRequestUtil.sendPost:%s", e));
			return "";
		}
	}

	public static String sendPost(String strURL, String param) {
		try {
			return httpPost(null, strURL, param, StringUtils.EMPTY);
		} catch (Exception e) {
			LOGGER.error(String.format("HttpRequestUtil.sendPost:%s", e));
			return "";
		}
	}

	public static String httpPost(String sessionId, String strURL, String param, String ssoSid) throws Exception {
//		if (StringUtils.isEmpty(sessionId)) {
//			sessionId = SessionInfoUtil.getSessionId();
//		}
		// 创建连接
		strURL = getBfsUrl(strURL);
		URL url = new URL(strURL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setRequestMethod("POST");
		connection.setUseCaches(false);
		connection.setInstanceFollowRedirects(true);
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
		connection.setRequestProperty("LocalReferer", "127.0.0.1");
		if (StringUtil.isNotEmpty(ssoSid)) {
			// connection.setRequestProperty("Cookie", "sid=" + sessionId +
			// ";JSESSIONID=" + ssoSid + ";");
			connection.setRequestProperty("Cookie", "sid=" + sessionId + ";JSESSIONID=" + sessionId + ";");
		} else {
			connection.setRequestProperty("Cookie", "sid=" + sessionId + ";JSESSIONID=" + sessionId + ";");
		}
		connection.connect();

		// POST请求
		DataOutputStream out = new DataOutputStream(connection.getOutputStream());

		String encodeParam = encodeParam(param);
		out.writeBytes(encodeParam);
		out.flush();
		out.close();

		// 读取响应
		BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
		String lines;
		StringBuilder sb = new StringBuilder();
		while ((lines = reader.readLine()) != null) {
			lines = new String(lines.getBytes("UTF-8"), "ISO-8859-1");
			lines = new String(lines.getBytes("ISO-8859-1"), "UTF-8");
			sb.append(lines);
		}

		reader.close();

		// 断开连接
		connection.disconnect();

		return sb.toString();
	}

	/**
	 * 方法描述:对参数进行UTF-8的编码.
	 *
	 * @param param
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String encodeParam(String param) throws UnsupportedEncodingException {
		if (StringUtils.isBlank(param)) {
			return param;
		}
		String noNeedEncodeChar1 = URLEncoder.encode("=", "utf-8");
		String noNeedEncodeChar2 = URLEncoder.encode("&", "utf-8");
		String encodeParam = URLEncoder.encode(param, "utf-8");
		encodeParam = encodeParam.replace(noNeedEncodeChar1, "=");
		encodeParam = encodeParam.replace(noNeedEncodeChar2, "&");
		return encodeParam;
	}

	public static String getSidCookieInfo(HttpServletRequest requ, String cookieName) {
		String sessionId = null;
		if (requ != null) {
			Cookie[] cookies = requ.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (!cookie.getName().equals(cookieName)) {
						continue;
					}
					if (!"null".equals(cookie.getValue())) {
						sessionId = cookie.getValue();
					}
				}
			}
			
			if (StringUtil.isEmpty(sessionId)) {
				sessionId = requ.getHeader(cookieName);
			}
		}

		return sessionId;
	}

	/**
	 * 
	 * getBfsUrl:(转换为本地IP地址).
	 *
	 * @param url
	 * @return
	 */
	public static String getBfsUrl(String url) {
		String ip = null;
		String regex = "http://.+?/";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(url);
		if (m.find()) {
			ip = m.group();
		}
		String localhostIp = null;
		String localhostPort = null;
		// 读取配置文件的ID地址
		localhostIp = PropertiesUtil.getValue("PUBLISH_SERVER_IP");
		if (StringUtil.isEmpty(localhostIp)) {
			localhostIp = "127.0.0.1";
		}
		// 读取配置文件的端口
		localhostPort = PropertiesUtil.getValue("PUBLISH_SERVER_PORT");
		if (StringUtil.isEmpty(localhostPort)) {
			localhostPort = "8080";
		}
		localhostIp = "http://" + localhostIp + ":" + localhostPort + "/";
		if (StringUtil.isEmpty(ip)) {
			url = localhostIp + url;
		} else {
			url = url.replace(ip, localhostIp);
		}

		return url;
	}
}